package com.magicmovie.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.magicmovie.entity.ViewHistory;
import com.magicmovie.mapper.ViewHistoryMapper;
import com.magicmovie.service.ViewHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Map;

@Service
public class ViewHistoryServiceImpl implements ViewHistoryService {
    @Autowired
    private ViewHistoryMapper viewHistoryMapper;

    @Override
    @Transactional(readOnly = false)
    public void insert(@RequestBody ViewHistory viewHistory) {
        ViewHistory v = viewHistoryMapper.findByCustomerAndMovie(viewHistory.getCustomerId(),viewHistory.getMovieId());
        if(v != null)
            viewHistoryMapper.deleteByPrimaryKey(v.getId());
        viewHistoryMapper.insert(viewHistory);
    }

    @Override
    public Map<String, Object> findByCustomerId(Integer customerId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize,true,false);
        Page<Map<String, Object>> page = viewHistoryMapper.findByCustomerId(customerId);
        Map<String,Object> map = Maps.newHashMap();
        map.put("result",page.getResult());
        map.put("pageNum",page.getPageNum());
        map.put("pages",page.getPages());
        map.put("total",page.getTotal());
        return map;
    }
}
